<?php
	require('order.doc.php');
	ini_set('display_errors','On');
	//创建课程订单
	$app->post(
		'/order/curriculum/add',
		function() use($app, $db2){
			$data = $app->request()->post();
			$echo['error'] = "";
			if($data && isset($data['memberid']) && isset($data['price']) && isset($data['curriculumid']) && isset($data['number'])){
				$curriculum = $db2->select(1, 'tb_curriculum', '*', array('tbid' => $data['curriculumid']));
				$curriculumsku = $db2->select(1, 'tb_curriculum_section_discount', '*', array('curriculum_id' => $data['curriculumid'], 'start_sec[<=]'=>$data['number'], 'end_sec[>=]'=>$data['number'], 'limit'=>'0,1'));
				
				if(!$curriculumsku){
				    $curriculumsku = array('discount' => 10);
				}
				
				if($curriculum && $curriculumsku){
					$idcode = getordernum('OD');
					//生成快照
					$db2->insert('tb_curriculum_snap', array(
						'idcode' => $idcode,
						'curriculum_id' => $data['curriculumid'],
						'title' => $curriculum['title'],
						'img' => $curriculum['img'],
						'intro' => $curriculum['intro'],
						'introimg' => $curriculum['introimg'],
						'price' => $curriculum['price'],
						'type' => $curriculum['type'],
						'coach_id' => $curriculum['coach_id'],
						'number' => $data['number'],
						'sku_discount' => $curriculumsku['discount']
					));
					//检查一遍价格是否正确
					$price = $curriculum['price'] * $data['number'] * $curriculumsku['discount'] / 10;
					if($price != $data['price']){
						$data['price'] = $price;
					}
					//生成订单
					$orderid = $db2->insert('tb_order', array(
						'idcode' => $idcode,
						'good_id' => $data['curriculumid'],
						'userid' => $data['memberid'],
						'usertype' => 1,
						'price' => $data['price'],
						'type' => 1,
						'#dt' => 'now()'
					));
					$db2->update('tb_curriculum',array('sales'=>$curriculum['sales']+1), array('tbid' => $data['curriculumid']));
					$echo['orderid'] = $orderid;
					$echo['orderidcode'] = $idcode;
				}else{
					$echo['error'] = "数据异常，请重试";
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	//创建特权订单
	$app->post(
		'/order/privilege/add',
		function() use($app, $db2){
			$data = $app->request()->post();
			$echo['error'] = "";
			if($data && isset($data['memberid']) && isset($data['price']) && isset($data['privilegeid'])){
				$privilege = $db2->select(1, 'tb_privilege', '*', array('tbid' => $data['privilegeid']));
				if($privilege){
					$idcode = getordernum('OD');
					//检查一遍价格是否正确
					if($privilege['price'] != $data['price']){
						$data['price'] = $privilege['price'];
					}
					//生成快照
					$db2->insert('tb_privilege_snap', array(
						'idcode' => $idcode,
						'lasting' => $privilege['lasting'],
						'price' => $data['price']
					));
					//生成订单
					$orderid = $db2->insert('tb_order', array(
						'idcode' => $idcode,
						'good_id' => $data['privilegeid'],
						'userid' => $data['memberid'],
						'usertype' => 1,
						'price' => $data['price'],
						'type' => 2,
						'#dt' => 'now()'
					));
					$echo['orderid'] = $orderid;
					$echo['orderidcode'] = $idcode;
				}else{
					$echo['error'] = "数据异常，请重试";
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	//创建场地订单
	$app->post(
		'/order/place/add',
		function() use($app, $db2){
			$data = $app->request()->post();
			$echo['error'] = "";
			if($data && isset($data['userid']) && isset($data['usertype']) && isset($data['price']) && isset($data['placeid']) && isset($data['reservetime']) && isset($data['reservedt'])){
				$place = $db2->select(1, 'tb_place', '*', array('tbid' => $data['placeid']));
				$snap=$db2->select(2,'tb_place_snap',array('[><]tb_order'=>array('idcode')),'*',array('place_id'=>$data['placeid'],'reservedt' => $data['reservedt'],'reservetime' => $data['reservetime'],'tb_order.state[!]'=>array(0,1)));
				if($place && $snap==0){
					$idcode = getordernum('OD');
					//生成快照
					$db2->insert('tb_place_snap', array(
						'idcode' => $idcode,
						'place_id' => $data['placeid'],
						'gym_id' => $place['gym_id'],
						'name' => $place['name'],
						'img' => $place['img'],
						'intro' => $place['intro'],
						'people' => $place['people'],
						'price' => $place['price'],
						'monday' => $place['monday'],
						'tuesday' => $place['tuesday'],
						'wednesday' => $place['wednesday'],
						'thursday' => $place['thursday'],
						'friday' => $place['friday'],
						'saturday' => $place['saturday'],
						'sunday' => $place['sunday'],
						'reservedt' => $data['reservedt'],
						'reservetime' => $data['reservetime']
					));
					//检查一遍价格是否正确
					if($place['price'] != $data['price']){
						$data['price'] = $place['price'];
					}
					//生成订单
					$orderid = $db2->insert('tb_order', array(
						'idcode' => $idcode,
						'good_id' => $data['placeid'],
						'userid' => $data['userid'],
						'usertype' => $data['usertype'],
						'price' => $data['price'],
						'type' => 3,
						'#dt' => 'now()'
					));
					$echo['orderid'] = $orderid;
					$echo['orderidcode'] = $idcode;
				}else{
					$echo['error'] = "场地已被购买，请选择其他场地";
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	//创建场地课程订单
	$app->post(
		'/order/place/curriculum/add',
		function() use($app, $db2){
			$data = $app->request()->post();
			$echo['error'] = "";
			if($data && isset($data['memberid']) && isset($data['price']) && isset($data['placecurriculumid'])){
				$placecurriculum = $db2->select(1, 'tb_place_curriculum', '*', array('tbid' => $data['placecurriculumid']));
				if(($placecurriculum['people']-1)>=$db2->select(2,'tb_place_curriculum_snap','*',array('place_curriculum_id'=>$placecurriculum['tbid']))){
					if($placecurriculum){
						$idcode = getordernum('OD');
						//生成快照
						$db2->insert('tb_place_curriculum_snap', array(
							'idcode' => $idcode,
							'place_id' => $placecurriculum['place_id'],
							'place_curriculum_id' => $data['placecurriculumid'],
							'title' => $placecurriculum['title'],
							'img' => $placecurriculum['img'],
							'intro' => $placecurriculum['intro'],
							'introimg' => $placecurriculum['introimg'],
							'price' => $placecurriculum['price'],
							'type' => $placecurriculum['type'],
							'coach_id' => $placecurriculum['coach_id'],
							'isfree' => $placecurriculum['isfree'],
							'people' => $placecurriculum['people']
						));
						//检查一遍价格是否正确
						if($placecurriculum['price'] != $data['price']){
							$data['price'] = $placecurriculum['price'];
						}
						$set=array(
							'idcode' => $idcode,
							'good_id' => $data['placecurriculumid'],
							'userid' => $data['memberid'],
							'usertype' => 1,
							'price' => $data['price'],
							'type' => 4,
							'#dt' => 'now()'
						);
						if($placecurriculum['isfree']==1){
							$set['state']=3;
						}
						//生成订单
						$orderid = $db2->insert('tb_order', $set);
						$echo['orderid'] = $orderid;
						$echo['orderidcode'] = $idcode;
					}else{
						$echo['error'] = "数据异常，请重试";
					}
				}else{
					$echo['error'] = "预约人数已满";
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	//创建商品订单
	$app->post(
		'/order/good/add',
		function() use($app, $db2){
			$data = $app->request()->post();
			$echo['error'] = "";
			if($data && isset($data['gymid']) && isset($data['info']) && isset($data['price'])){
				$info=authcode($data['info'], 'DECODE', 'adaa');
				if(!$info){
					$echo['error'] = "二维码已超时，请刷新后重试";
					echo json_encode($echo);exit;
				}else{
					$info=explode(',',$info);
					if(count($info)!=2){
						$echo['error'] = "不是正确的付款二维码";
						echo json_encode($echo);exit;
					}
					$data['userid']=$info[0];
					$data['usertype']=$info[1];
				}
				$idcode = getordernum('OD');
				//生成订单
				$orderid = $db2->insert('tb_order', array(
					'idcode' => $idcode,
					'userid' => $data['userid'],
					'usertype' => $data['usertype'],
					'gym_id' => $data['gymid'],
					'price' => $data['price'],
					'type' => 5,
					'#dt' => 'now()'
				));
				$echo['orderid'] = $orderid;
				$echo['orderidcode'] = $idcode;
				//回参数：真实姓名、会员ID(手机号)、应付金额、实付金额、消费ADAA币、类型（会员/教练）、VIP会员到期时间、教练等级
				if($data['usertype']==1){
					$tb='tb_member';
				}else{
					$tb='tb_coach';
				}
				$user=$db2->select(1,$tb,'*',array('tbid'=>$data['userid']));
				$echo['realname']=$user['realname'];
				$echo['mobile']=$user['mobile'];
				$echo['price']='¥'.$data['price'];
				if($data['usertype']==1){
					$echo['type']='会员';
					if(strtotime($user['privilege_dt'])>=time()){
						$echo['privilege_dt']='VIP会员';
						$discount=0.8;
					}else{
						$echo['privilege_dt']='非VIP会员';
						$discount=1;
					}
				}else{
					$echo['type']='教练';
					switch($user['level']){
						case 0:$echo['level']='淘汰';$discount=1;break;
						case 1:$echo['level']='银牌';$discount=1;break;
						case 2:$echo['level']='金牌';$discount=0.95;break;
						case 3:$echo['level']='钻石';$discount=0.9;break;
					}
				}
				$echo['trademoney']=$data['price'];
				if($user['adaa']>0){
					if($user['adaa']<$data['price']/2){
						$adaa=$user['adaa'];
					}elseif($user['adaa']>=$data['price']/2){
						$adaa=$data['price']/2;
					}
					$data['price']-=$adaa;
					$echo['tradeadaa']=$adaa;
				}
				if(!$echo['trademoney']){
					$echo['trademoney']=0;
				}else{
					$echo['trademoney']='¥'.abs($echo['trademoney']);
				}
				if(!$echo['tradeadaa']){
					$echo['tradeadaa']=0;
				}else{
					$echo['tradeadaa']='¥'.abs($echo['tradeadaa']);
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			$echo['gymid']=$data['gymid'];
			$echo['userid']=$data['userid'];
			$echo['usertype']=$data['usertype'];
			echo json_encode($echo);
		}
	);
	
	
	//创建团队课程订单
	$app->post(
	    '/order/group/curriculum/add',
	    function() use($app, $db2){
	        $data = $app->request()->post();
	        $echo['error'] = "";
	        if($data && isset($data['memberid']) && isset($data['price']) && isset($data['groupcurriculumid'])){
	            $placecurriculum = $db2->select(1, 'tb_group_curriculum', '*', array('tbid' => $data['groupcurriculumid']));
	            if(($placecurriculum['people']-1)>=$db2->select(2,'tb_group_curriculum_snap','*',array('group_curriculum_id'=>$placecurriculum['tbid']))){
	                if($placecurriculum){
	                    $idcode = getordernum('OD');
	                    //生成快照
	                    $db2->insert('tb_group_curriculum_snap', array(
	                        'idcode' => $idcode,
	                        'group_curriculum_id' => $data['groupcurriculumid'],
	                        'gym_id' => $placecurriculum['gym_id'],
	                        'title' => $placecurriculum['title'],
	                        'img' => $placecurriculum['img'],
	                        'intro' => $placecurriculum['intro'],
	                        'introimg' => $placecurriculum['introimg'],
	                        'price' => $placecurriculum['price'],
	                        'type' => $placecurriculum['type'],
	                        'coach' => $placecurriculum['coach'],
	                        'isfree' => $placecurriculum['isfree'],
	                        'people' => $placecurriculum['people'],
	                        //'level' => $placecurriculum['level'],
	                        //'pumped' => $placecurriculum['pumped'],
	                        'peaktime' => $placecurriculum['peaktime'],
	                        'peakofftime' => $placecurriculum['peakofftime'],
	                        'burningfat' => $placecurriculum['burningfat']
	                    ));
	                    //检查一遍价格是否正确
	                    if($placecurriculum['price'] != $data['price']){
	                        $data['price'] = $placecurriculum['price'];
	                    }
	                    $set=array(
	                        'idcode' => $idcode,
	                        'good_id' => $data['groupcurriculumid'],
	                        'userid' => $data['memberid'],
	                        'usertype' => 1,
	                        'price' => $data['price'],
	                        'type' => 6,
	                        '#dt' => 'now()'
	                    );
	                    if($placecurriculum['isfree']==1){
	                        $set['state']=3;
	                    }
	                    //生成订单
	                    $orderid = $db2->insert('tb_order', $set);
	                    $echo['orderid'] = $orderid;
	                    $echo['orderidcode'] = $idcode;
	                }else{
	                    $echo['error'] = "数据异常，请重试";
	                }
	            }else{
	                $echo['error'] = "购买人数已满";
	            }
	        }else{
	            $echo['error'] = "数据缺失，请检查";
	        }
	        echo json_encode($echo);
	    }
	);
	
	
	$app->get(
		'/order/get',
		function() use($app, $db2, $file_split, $file_subsplit){
			$data = $app->request()->get();
			$echo['error'] = "";
			if($data && isset($data['from']) && isset($data['to']) && isset($data['userid']) && isset($data['usertype'])){
				if($data['usertype'] == 1){
					$sqlwhere['member_id'] = $data['userid'];
				}else{
					$sqlwhere['coach_id'] = $data['userid'];
				}
				if(isset($data['state'])){
					$sqlwhere['state'] = $data['state'];
				}
				if(isset($data['type'])){
					$sqlwhere['type'] = $data['type'];
				}
				$echo['count'] = $db2->select(2, 'tb_order', '*', $sqlwhere);
				$sqlwhere['limit'] = array($data['from'], $data['to']);
				$sqlwhere['order'] = 'dt desc';
				foreach($db2->select(0, 'tb_order', '*', $sqlwhere) as $v){
					$tmp['orderid'] = $v['tbid'];
					$tmp['idcode'] = $v['idcode'];
					$tmp['price'] = $v['price'];
					$tmp['state'] = $v['state'];
					$tmp['type'] = $v['type'];
					if($v['type'] == 1){
						$tmp['curriculumid'] = $v['curriculum_id'];
						$tmp['curriculumtitle'] = $v['curriculum_title'];
						$tmp['curriculumimg'] = $v['curriculum_img'];
						$tmp['curriculumintro'] = $v['curriculum_intro'];
						$tmp['curriculumintroimg'] = $v['curriculum_introimg'];
						$tmp['curriculumprice'] = $v['curriculum_price'];
						$tmp['curriculumtype'] = $v['curriculum_type'];
						$tmp['curriculumskuid'] = $v['curriculum_sku_id'];
						$tmp['curriculumskunumber'] = $v['curriculum_sku_number'];
						$tmp['curriculumskudiscount'] = $v['curriculum_sku_discount'];
					}
					$echo['data'][] = $tmp;
					unset($tmp);
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	$app->get(
		'/order/info',
		function() use($app, $db2, $file_split, $file_subsplit){
			$data = $app->request()->get();
			$echo['error'] = "";
			if($data && isset($data['orderid']) && isset($data['userid']) && isset($data['usertype'])){
				$sqlwhere['tbid'] = $data['orderid'];
				if($data['usertype'] == 1){
					$sqlwhere['member_id'] = $data['userid'];
				}else{
					$sqlwhere['coach_id'] = $data['userid'];
				}
				$order = $db2->select(1, 'tb_order', '*', $sqlwhere);
				$echo['idcode'] = $order['idcode'];
				$echo['price'] = $order['price'];
				$echo['idcode'] = $order['idcode'];
				$echo['idcode'] = $order['idcode'];




				$echo['ordernumber'] = $order['ordernumber'];
				$echo['total'] = $order['total'];
				$echo['name'] = $order['name'];
				$echo['phone'] = $order['phone'];
				$echo['address'] = $order['address'];
				$echo['remark'] = $order['remark'];
				$echo['state'] = $order['state'];
				$echo['builddt'] = $order['builddt'];
				$echo['closedt'] = $order['closedt'];
				$echo['paymentdt'] = $order['paymentdt'];
				$echo['deliverydt'] = $order['deliverydt'];
				$echo['confirmdt'] = $order['confirmdt'];
				$echo['paymenttype'] = $order['paymenttype'];
				$echo['expresscompany'] = $order['expresscompany'];
				$echo['expressnumber'] = $order['expressnumber'];
				$echo['type'] = $order['type'];
				if($order['type'] == 1 || $order['type'] == 3){
					foreach($db2->select(0, 'tb_order_good', '*', array('order_id' => $data['orderid'])) as $v){
						$tmp['ordergoodid'] = $v['tbid'];
						$tmp['goodid'] = $v['good_id'];
						$tmp['title'] = $v['title'];
						foreach(explode($file_split, $v['img']) as $img){
							if($img != ''){
								$dom = explode($file_subsplit, $img);
								$tmp['img'] = $dom[0];
								$tmp['simg'] = getFileInfo($dom[0], 'simg');
								break;
							}
						}
						if($v['prop']){
							foreach(json_decode($v['prop']) as $kk => $kkv){
								$tmp['prop'][] = $kk;
							}
						}else{
							$tmp['prop'] = array();
						}
						$tmp['portattr'] = $v['portattr'];
						$good = $db2->select(1, 'tb_goods', '*', array('tbid' => $v['good_id']));
						$tmp['ishave'] = $good['portattr']->$v['portattr'] ? true : false;
						$tmp['count'] = $v['count'];
						$tmp['price'] = $v['price'];
						$tmp['total'] = $v['total'];
						$service = $db2->select(1, 'tb_customer_service', '*', array('userid' => $data['memberid'], 'ordernumber' => $order['ordernumber'], 'good_id' => $v['tbid'],'order'=>'tbid desc'));
						if($service['cstate']==6 || $service['cstate']==4){
							unset($service);
						}
						$tmp['cstate'] = $service ? $service['cstate'] : '';
						$echo['goods'][] = $tmp;
						unset($tmp);
					}
				}else if($order['type'] == 2){
					foreach($db2->select(0, 'tb_order_wish', '*', array('order_id' => $order['tbid'])) as $v){
						$tmp['orderwishid'] = $v['tbid'];
						$tmp['wishid'] = $v['wish_id'];
						$tmp['title'] = $v['title'];
						foreach(explode($file_split, $v['img']) as $img){
							if($img != ''){
								$dom = explode($file_subsplit, $img);
								$tmp['img'] = $dom[0];
								$tmp['simg'] = getFileInfo($dom[0], 'simg');
								break;
							}
						}
						$tmp['price'] = $v['price'];
						$tmp['enddt'] = $v['enddt'];
						$echo['wish'][] = $tmpp;
						unset($tmp);
					}
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	$app->post(
		'/order/close',
		function() use($app, $db2){
			$data = $app->request()->post();
			$echo['error'] = "";
			if($data && isset($data['memberid']) && isset($data['orderid'])){
				$order = $db2->select(1, 'tb_order', '*', array('tbid' => $data['orderid'], 'member_id' => $data['memberid']));
				if($order['state'] == 1){
					if($db2->select(2,'tb_trade','*',array('orderid'=>$order['ordernumber'],'state'=>0,'type'=>1))>0){
						updategoodsstock($order['ordernumber'],1);
						$db2->update('tb_trade',array('state'=>2),array('type'=>array(0,1),'orderid'=>$order['ordernumber']));
					}
					$db2->update('tb_order', array('state' => 0, 'closedt' => date('Y-m-d H:i:s')), array('tbid' => $order['tbid']));
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	$app->post(
		'/order/payment',
		function() use($app, $db2){
			$data = $app->request()->post();
			$echo['error'] = "";
			if($data && isset($data['memberid']) && isset($data['orderid']) && isset($data['paymenttype']) && isset($data['serialnumber'])){
				$order = $db2->select(1, 'tb_order', '*', array('tbid' => $data['orderid'], 'member_id' => $data['memberid']));
				if($order['state'] == 1){
					$member = $db2->select(1, 'tb_member', '*', array('tbid' => $data['memberid']));
					if($member['balance'] >= $order['total']){
						$db2->update('tb_member', array('balance[-]' => $order['total']), array('tbid' => $data['memberid']));
						$db2->insert('tb_moneychange', array('money' => $order['total'], 'type' => 2, 'serialnumber' => $data['serialnumber'], 'ordernumber' => $order['ordernumber'], 'member_id' => $data['memberid'], 'dt' => date('Y-m-d H:i:s')));
						$db2->update('tb_order', array('state' => 2, 'paymentdt' => date('Y-m-d H:i:s'), 'paymenttype' => $data['paymenttype']), array('tbid' => $order['tbid']));
					}else{
						$echo['error'] = "账户余额不足，请充值";
					}
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	$app->post(
		'/order/confirm',
		function() use($app, $db2){
			$data = $app->request()->post();
			$echo['error'] = "";
			if($data && isset($data['memberid']) && isset($data['orderid'])){
				$order = $db2->select(1, 'tb_order', '*', array('tbid' => $data['orderid'], 'member_id' => $data['memberid']));
				if($order['state'] == 3){
					$db2->update('tb_order', array('state' => 4, 'confirmdt' => date('Y-m-d H:i:s')), array('tbid' => $order['tbid']));
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	$app->post(
		'/order/delete',
		function() use($app, $db2){
			$data = $app->request()->post();
			$echo['error'] = "";
			if($data && isset($data['memberid']) && isset($data['orderid'])){
				$order = $db2->select(1, 'tb_order', '*', array('tbid' => $data['orderid'], 'member_id' => $data['memberid']));
				if($order['state'] == 4 || $order['state'] == 0){
					$db2->update('tb_order', array('isdelete' => 1), array('tbid' => $order['tbid']));
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	$app->post(
		'/order/good/comment',
		function() use($app, $db2){
			$data = $app->request()->get();
			$echo['error'] = "";
			if($data && isset($data['memberid']) && isset($data['goodid']) && isset($data['ordergoodid']) && isset($data['content']) && isset($data['star']) && isset($data['type'])){
				if(!empty($_FILES)){
					$img = creatfilesimg($_FILES,'',$data['memberid']);
				}
				$commentid = $db2->insert(2, 'tb_good_comment', array(
					'img' => $img,
					'content' => $data['content'],
					'star' => $data['star'],
					'dt' => date('Y-m-d H:i:s'),
					'type' => $data['type'],
					'good_id' => $data['goodid'],
					'member_id' => $data['memberid']
				));
				$db2->update('tb_order_good', array('comment_id' => $commentid), array('tbid' => $data['ordergoodid']));
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
?>
